#! /bin/bash

# 获取环境变量
PLAY_HOME=/opt/playground

function installK8s()
{
 #1.在frames.txt中查看是否需要安装k8s
 k8sInfo=`egrep "^k8s" ../frames.txt`

 k8s=`echo $k8sInfo | cut -d " " -f1`
 isInstall=`echo $k8sInfo | cut -d " " -f2`
 k8sNodes=`echo $k8sInfo | cut -d " " -f3` 
 masterNode=`echo $k8sInfo | cut -d " " -f4` 
 node=`hostname`

 masterInfo=`egrep "$masterNode" ../host_ip.txt`
 masterIP=`echo $masterInfo | cut -d " " -f1`

 #是否安装
 if [[ $isInstall = "true" && $masterNode = $node ]];then
    
     #2.查看/opt/frames目录下是否有k8s安装包
     k8sIsExists=`find /opt/frames -name $k8s`

     if [[ ${#k8sIsExists} -ne 0 ]];then

          # 离线方式安装
          echo "离线方式安装"

     else
        echo "/opt/frames目录下没有k8s安装包，开始在线安装"
        #遍历配置安装节点
        OLD_IFS="$IFS" #保存旧的分隔符
        IFS=","
        nodes=($k8sNodes)
        IFS="$OLD_IFS" # 将IFS恢复成原来的
        for i in "${!nodes[@]}"; do
            # 循环初始化k8s环境
            ssh -n ${nodes[i]} $PLAY_HOME/systems/preK8sConfig.sh
        done
    
         kubeadm init --kubernetes-version=v1.19.0 --pod-network-cidr=10.244.0.0/16 --service-cidr=10.96.0.0/12 --apiserver-advertise-address $masterIP > /tmp/k8s.tmp
         
         mkdir -p $HOME/.kube
         sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
         sudo chown $(id -u):$(id -g) $HOME/.kube/config

         slave_str=`tail -n 2 /tmp/k8s.tmp`
         slave_join=`echo $slave_str | sed 's/\\\//g'`
         for i in "${!nodes[@]}"; do
            if [[ ${nodes[i]} != $masterNode ]];then
            # 添加slave节点
            ssh -n ${nodes[i]} $slave_join
            # 拷贝配置文件到slave节点
            scp /etc/kubernetes/admin.conf root@${nodes[i]}:`pwd`
            # 执行初始化
            ssh -n ${nodes[i]} "mkdir -p \$HOME/.kube"
            # ssh -n ${nodes[i]} "cp -i /etc/kubernetes/admin.conf \$HOME/.kube/config"
            scp /etc/kubernetes/admin.conf root@${nodes[i]}:$HOME/.kube/config
            ssh -n ${nodes[i]} "chown $(id -u):$(id -g) \$HOME/.kube/config"
            fi
        done

        # 安装Flannel
        flannelIsExists=`find /opt/frames -name kube-flannel.yaml`
        if [[ ${#flannelIsExists} -ne 0 ]];then
            # 直接离线安装
            kubectl apply -f /opt/frames/kube-flannel.yaml
        else
            # 在线安装
            kubectl apply -f https://raw.githubusercontent.com/coreos/flannel/master/Documentation/kube-flannel.yml
        fi
        
     fi
 else
     echo "K8S需要在主节点进行安装，请检查配置文件！"
 fi

}

installK8s
